﻿Imports System.Data.SqlClient

Public Class Login2
    Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        ' 获取用户输入
        Dim username As String = UsernameTextBox.Text.Trim()
        Dim password As String = PasswordTextBox.Text.Trim()

        ' 基本输入校验
        If username = "" Then
            MessageBox.Show("请输入用户名！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            UsernameTextBox.Focus()
            Exit Sub
        End If

        If password = "" Then
            MessageBox.Show("请输入密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            PasswordTextBox.Focus()
            Exit Sub
        End If

        ' 定义数据库连接字符串（请根据你自己的 SQL Server 设置修改）


        Using conn As New SqlConnection(DbConnectionHelper.GetConnectString())
            Try
                conn.Open()

                ' 构造 SQL 查询语句
                Dim sql As String = "SELECT COUNT(*) FROM USERK WHERE username=@username AND password=@password"

                Using cmd As New SqlCommand(sql, conn)
                    cmd.Parameters.AddWithValue("@username", username)
                    cmd.Parameters.AddWithValue("@password", password)

                    Dim count As Integer = Convert.ToInt32(cmd.ExecuteScalar())

                    If count > 0 Then
                        ' MessageBox.Show("登录成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                        mainView.Show()
                        WriteLog("123用户登录")

                        Me.Hide()
                    Else
                        MessageBox.Show("用户名或密码错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        WriteLog("用户名或密码错误！：" + username + "  " + password)
                    End If
                End Using

            Catch ex As Exception
                MessageBox.Show("数据库连接失败：" & ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
                WriteLog("数据库连接失败：" & ex.Message)
            End Try
        End Using
    End Sub
End Class